package cn.shiwei.hr.handler;

import cn.shiwei.hr.repository.AjaxResult;
import com.alibaba.fastjson.JSON;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DefaultAccessDeniedHandler implements AccessDeniedHandler, AuthenticationEntryPoint {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(AjaxResult.me().setSuccess(false).setMessage("没有权限")));
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        e.printStackTrace();
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().print(JSON.toJSONString(AjaxResult.me().setSuccess(false).setMessage("登录失败: " + e.getMessage())));
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
